package com.hh.erp.interceptor;

import com.hh.erp.util.RedisUtil;
import com.hh.erp.util.StringUtil;
import com.hh.erp.util.http.Constants;
import com.hh.erp.util.http.DiscoveryException;
import com.hh.erp.util.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    /*
      不需要拦截的接口
     */
    private static List<String> requestUrls = Arrays.asList("/system/login", "/system/logout");
    /**
     * 目标方法执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getServletPath();  //获取请求路径 如果是登录请求，则不用检查token 是否为空
        if(requestUrls.contains(requestUrl)) {
            return true;
        }
        String token = request.getHeader(Constants.AutoToken);  // token 不为空，且在redis 存在
        if(StringUtil.IsSpace(token) || !RedisUtil.containsKey(token)) {
            throw new DiscoveryException(HttpStatus.AULOGIN,"用户信息已过期，请先登陆 !");
        } else {
            //放行
            return true;
        }
    }
    /**
     * 目标方法执行后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("目标方法执行后......");
    }
    /**
     * 页面渲染后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
